package com.atxiao.controller;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import org.apache.commons.io.IOUtils;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;


import java.io.*;
import java.util.*;

@RestController
public class testController {


    @RequestMapping("/test1/{filename}")
    public List testDemo2(@PathVariable("filename") String filename) throws Exception {


        String filepath="/home/demo/";
        String type=".txt";
        ArrayList<String> list = new ArrayList<>();

        File file = new File(filepath + filename+type);
        FileWriter fileWriter = new FileWriter(file, false);
        fileWriter.write("aaaaaa");
        fileWriter.close();
        list.add("操作成功");
        return list;

    }



    @RequestMapping("/test2/{filename}")
    public List testDemo(@PathVariable("filename") String filename){


        String filepath="/home/demo/";
        String type=".txt";
        ArrayList<String> list = new ArrayList<>();
        String res="";
        try {
            File file = new File(filepath + filename+type);
//            if (!file.exists()){
//                file.createNewFile();
//            }
            System.out.println(file.getAbsolutePath());
            list.add(file.getAbsolutePath());
            BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(new FileInputStream(file)));
            while ((res=bufferedReader.readLine())!=null){
                list.add(res);
            }


        } catch (Exception e) {
            e.printStackTrace();
        }
        return list;

    }


    //添加商户(以Json对象的方式添加到文件中)
    @RequestMapping("/addMerchatByBean")
    public boolean addMerchatWithBean(
                              @RequestBody JSONObject jsonObject,
                              @RequestBody JSONArray Arrays
    ) throws IOException {

        System.out.println("接收到的参数："+jsonObject);
        System.out.println("转换后的参数格式："+jsonObject.toJSONString());

        Object merID = jsonObject.get("merID");
        Object merName = jsonObject.get("merName");

//        String mer="[" +"{"+
//                "merID"+":"+merID+
//                ","+
//                "merName"+":"+merName+
//                "}"+"]";
//        System.out.println(mer);

//        JSONArray jsonArray = JSON.parseArray(mer);

        String fileType=".txt";
        String filepath="/home/local/demo/";
        String filename=merID+fileType;

        File file = new File(filepath);
        if (!file.exists()){
//            boolean flag = file.createNewFile();
//            System.out.println(flag);
            file.mkdirs();
            System.out.println("创建文件夹成功~~~");

        }

        File file1 = new File(filepath + filename);
        if (!file1.exists()){
            file1.createNewFile();
            System.out.println("创建文件成功~~~");
        }


        FileWriter fileWriter = new FileWriter(filepath+filename, true);
        StringBuilder sb = new StringBuilder();
        String merchantmsg = jsonObject.toJSONString();



        fileWriter.write(jsonObject.toJSONString());
        fileWriter.close();
        System.out.println("文件存储成功~~~");


//        for (Object o : jsonArray) {
//            JSONObject object= (JSONObject) o;
//            Object merID1 = object.get("merID");
//            System.out.println("merID="+merID1);
//            Object merName1 = object.get("merName");
//            System.out.println("merName="+merName1);
//        }


        return true;
    }










    //添加商户(以Json数组的方式添加到文件中)
    @RequestMapping("/addMerchatByArray")
    public boolean addMerchatWithArray(
//            @RequestBody JSONObject jsonObject,
            @RequestBody JSONArray arrays
    ) throws IOException {
        //参数数组
        ArrayList<String> paramList = new ArrayList<>();
        //结果数组
        ArrayList<String> resList = new ArrayList<>();

        System.out.println("接收到的参数："+arrays);
        System.out.println("转换后的参数格式："+arrays.toJSONString());
        String fileType=".txt";
        String filepath="/home/local/demo/";
        String filename="allMerList"+fileType;

//        //重复不可添加
//        for (Object array : arrays) {
//
//            JSONObject bean= (JSONObject) array;
//            String merID = (String) bean.get("merID");
//            paramList.add(merID);
//
//        }




        File file = new File(filepath);
        if (!file.exists()){
            file.mkdirs();
            System.out.println("创建文件夹成功~~~");
        }

        File file1 = new File(filepath + filename);
        if (!file1.exists()){
            try {
                file1.createNewFile();
            } catch (IOException e) {
                e.printStackTrace();
            }
            System.out.println("创建文件成功~~~");
        }






        JSONArray paramArray = JSONObject.parseArray(arrays.toJSONString());
        for (Object o : paramArray) {
            JSONObject bean= (JSONObject) o;
            String merID = (String) bean.get("merID");
            paramList.add(merID);
        }


        FileInputStream fis = new FileInputStream(filepath+filename);
        //文件中的内容数组
        JSONArray jsonArray = JSONObject.parseArray(IOUtils.toString(fis, "utf-8"));
        int size = jsonArray.size();

        if (size>0){
            for (Object o : jsonArray) {
                JSONObject bean= (JSONObject) o;
                String merID = (String) bean.get("merID");
                resList.add(merID);
            }
            //比较
            boolean flag = Collections.disjoint(paramList, resList);
            if (!flag){
                System.out.println("商户重复");
                throw new RuntimeException("商户重复");
            }
        }



        FileWriter fileWriter = null;
        try {
            fileWriter = new FileWriter(filepath+filename, true);
            fileWriter.write(arrays.toJSONString());
        } catch (IOException e) {
            e.printStackTrace();
        }finally{
            try {
                fileWriter.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }

        System.out.println("文件存储成功~~~");


//        for (Object o : jsonArray) {
//            JSONObject object= (JSONObject) o;
//            Object merID1 = object.get("merID");
//            System.out.println("merID="+merID1);
//            Object merName1 = object.get("merName");
//            System.out.println("merName="+merName1);
//        }


        return true;
    }





    //获取商户下拉框的列表（在文件中存储）
    @RequestMapping("/getMerList")
    public List<String> getMerList(
//                                   @RequestBody JSONObject jsonObject
    )throws IOException {
//        Object merID = jsonObject.get("merID");
        String fileType=".txt";
        String filepath="/home/local/demo/";
        String filename="allMerList"+fileType;

        ArrayList<String> list = new ArrayList<>();
//        String filepath="/home/aps/demo/"+merID+".txt";
        FileInputStream fis = new FileInputStream(filepath+filename);
        JSONArray jsonArray = JSONObject.parseArray(IOUtils.toString(fis, "utf-8"));
        for (Object o : jsonArray) {
            JSONObject object= (JSONObject) o;
            String name = (String) object.get("merName");
            list.add(name);
//            list.add(1,name);
        }
        return list;

    }


    @RequestMapping("/getAllMerList")
    public List<String> getAllMerList(){

        ArrayList<String> list = new ArrayList<>();
        String fileType=".txt";
        String filepath="/home/local/demo/";
        String filename="allMerList"+fileType;

        File file = new File(filepath);
        File[] files = file.listFiles();
        for (File file1 : files) {


            String name = file1.getName();

            list.add(name.substring(0,name.lastIndexOf(".")));
        }
        return list;
    }




}
